﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using Newtonsoft.Json.Linq;
using NjaNjam.MongoRepository;
using NjamNjam.Model.Entities;
using NjamNjamAdminApp.Interfaces;
using NjamNjamAdminApp.Models;
using System.Linq;
using NjamNjamAdminApp.Properties;

namespace NjamNjamAdminApp.Views
{
    public partial class PretragaRestoranaView : DevExpress.XtraEditors.XtraForm, IView
    {
        KriterijumiPretrageRestorana m_Kriterijumi = new KriterijumiPretrageRestorana();

        MongoRepository m_Repository = new MongoRepository();

        public PretragaRestoranaView()
        {
            InitializeComponent();
            kriterijumiPretrageRestoranaBindingSource.DataSource = m_Kriterijumi;
            
            btnPretrazi.Click += (s, e) => OnPretraziClicked();
            lookUpEdit1.ButtonClick += (s, e) =>
                                       {
                                           if (e.Button.Kind == ButtonPredefines.Delete)
                                           {
                                               lookUpEdit1.EditValue = null;
                                           }
                                       };
            btnPronadji.Click += (s, e) => OnPronadji();
            string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            string filePath = Path.Combine(appPath, "Web/Map.htm");
            webBrowser1.Url = new Uri(filePath);
            gridView1.RowClick += OnSelectedRow;
            KeyDown += (s, e) =>
                       {
                           if (e.KeyCode == Keys.Enter)
                           {
                               OnPretraziClicked();
                           }
                       };
            btnCancel.Click += (s, e) =>
                               {
                                   m_Kriterijumi = new KriterijumiPretrageRestorana();
                                   kriterijumiPretrageRestoranaBindingSource.DataSource = m_Kriterijumi;
                                   restoranBindingSource.DataSource = typeof (Restoran);
                                   webBrowser1.Document.InvokeScript("ocisti");
                               };
        }

        private void OnSelectedRow(object sender, RowClickEventArgs e)
        {
            var restoran = gridView1.GetFocusedRow() as Restoran;
            if (restoran != null)
            {
                webBrowser1.Document.InvokeScript("prikaziInfo", 
                    new object[]
                    {
                        restoran.Naziv, 
                        restoran.VrstaRestorana != null ? restoran.VrstaRestorana.Naziv : "", 
                        restoran.Adresa + ", " + restoran.Mesto, 
                        restoran.Latituda, restoran.Longituda,
                        restoran.RadnoVremeOd.ToShortTimeString() + " - " + restoran.RadnoVremeDo.ToShortTimeString()
                    });
            }
        }

        private void OnPronadji()
        {
            using (var dlg = new AddressSearchView(string.Empty))
            {
                dlg.ShowDialog(this);
                if (dlg.SearchResult != null)
                {
                    m_Kriterijumi.Latituda = dlg.SearchResult.Latitude;
                    m_Kriterijumi.Longituda = dlg.SearchResult.Longitude;
                }
            }
        }

        private void OnPretraziClicked()
        {
            try
            {
                ((IShell)MdiParent).StarLongRunningOperation("Pretraga u toku...");
                IEnumerable<Restoran> restorani = m_Repository.PretraziRestorane(m_Kriterijumi.Latituda,
                                                                                 m_Kriterijumi.Longituda,
                                                                                 m_Kriterijumi.Razdaljina / 1000,
                                                                                 m_Kriterijumi.VrstaRestorana,
                                                                                 m_Kriterijumi.IzabranaPonuda)
                                                                                 .Select(x => new Restoran
                                                                                 {
                                                                                     Id = x.Id,
                                                                                     Naziv = x.Naziv,
                                                                                     Latituda = x.Latituda,
                                                                                     Longituda = x.Longituda,
                                                                                     Adresa = x.Adresa,
                                                                                     Mesto = x.Mesto
                                                                                 });
                restoranBindingSource.DataSource = restorani;
                webBrowser1.Document.InvokeScript("ocisti");
                PrikaziNaMapi(restorani);
            }
            catch (Exception exc)
            {
                ((IShell)MdiParent).ShowWarning(exc.Message);
                throw;
            } finally
            {
                ((IShell)MdiParent).StopLongRunningOperation();
            }
        } 

        private void PrikaziNaMapi(IEnumerable<Restoran> restorani)
        {
            if (webBrowser1.Document != null)
            {
                if (m_Kriterijumi.Latituda.HasValue && m_Kriterijumi.Longituda.HasValue)
                {
                    webBrowser1.Document.InvokeScript("prikaziMe",
                                                      new object[] {m_Kriterijumi.Latituda, m_Kriterijumi.Longituda});
                }
                foreach (var restoran in restorani)
                {
                    webBrowser1.Document.InvokeScript("pozicioniraj",
                                                      new object[] { restoran.Latituda, restoran.Longituda, false });
                }
            }
        }

        private void UcitajVrsteRestorana()
        {
            vrstaRestoranaBindingSource.DataSource = m_Repository.VrsteRestorana().Select(x => new VrstaRestorana{Id = x.Id, Naziv = x.Naziv});
        }

        protected override void OnLoad(EventArgs e)
        {
        }

        public void NoviUnos()
        {
        }

        public void Sacuvaj()
        {
        }

        public void Obrisi()
        {
        }

        public void Osvezi()
        {
            UcitajVrsteRestorana();
            UcitajPonudu();
        }

        public void Izvezi()
        {
        }

        private void UcitajPonudu()
        {
            var ponuda = m_Repository.Ponuda().Select(x => new Ponuda{Id = x.Id, Naziv = x.Naziv, Slika = x.Slika}).ToArray();
            imageComboBoxEdit1.Properties.Items.Clear();
            imageList1.Images.Clear();
            for (int i = 0; i < ponuda.Count(); i++)
            {
                var p = ponuda[i];
                imageList1.Images.Add(p.Slika != null
                                          ? Image.FromStream(new MemoryStream(p.Slika))
                                          : Resources.camera_photo);
                imageComboBoxEdit1.Properties.Items.Add(new ImageComboBoxItem(p.Naziv, p, i));
            }
        }
    }
}